package com.misty.factory_pattern.singlefactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 这种单例模式极其不推荐，但是可以通过这种方式获得私有对象也是一个思路
 */
public class SingletonFactory {
    private static Singleton singleton;

    static {
        try {
            Class c = Class.forName(Singleton.class.getName());
            //获得无参构造器
            Constructor constructor = c.getDeclaredConstructor();
            //设置无参构造器可以访问 ,由于单例是对外隐藏构造器的，反射和原型模式一样会影响具体单例
            constructor.setAccessible(true);
            singleton = (Singleton) constructor.newInstance();
        } catch (ClassNotFoundException | NoSuchMethodException
                | IllegalAccessException | InstantiationException
                | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static Singleton getInstance() {
        return singleton;
    }
}
